package com.dz.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.dz.constant.*;
import com.dz.dto.EmployeeDTO;
import com.dz.dto.EmployeeLoginDTO;
import com.dz.dto.EmployeePageQueryDTO;
import com.dz.dto.PasswordEditDTO;
import com.dz.entity.Employee;
import com.dz.enumeration.AppHttpCodeEnum;
import com.dz.exception.AccountLockedException;
import com.dz.exception.AccountNotFoundException;
import com.dz.exception.PasswordErrorException;
import com.dz.exception.SystemException;
import com.dz.mapper.EmployeeMapper;
import com.dz.result.Result;
import com.dz.service.EmployeeService;
import com.dz.utils.BeanCopyUtils;
import com.dz.vo.EmployeeVo;
import com.dz.vo.PageVo;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /*
     * 新增员工
     * */
    @Override
    public Result<?> addEmployee(EmployeeDTO employeeDTO) {
        // 数据校验
        if (!StringUtils.hasText(employeeDTO.getUsername())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_ISNULL);
        }
        if (!employeeDTO.getPhone().matches(RegEx.PHONE_REG)) {
            throw new SystemException(AppHttpCodeEnum.PHONE_NUMBER_ERROR);
        }

        // 身份证格式校验
        if (employeeDTO.getIdNumber().length() == EmployeeConstant.ID_LENGTH_18) {
            if (!employeeDTO.getIdNumber().matches(RegEx.ID_CARD_REG18))
                throw new SystemException(AppHttpCodeEnum.ID_NUMBER_ERROR);
        } else if (employeeDTO.getIdNumber().length() == EmployeeConstant.ID_LENGTH_15) {
            if (!employeeDTO.getIdNumber().matches(RegEx.ID_CARD_REG15))
                throw new SystemException(AppHttpCodeEnum.ID_NUMBER_ERROR);
        } else throw new SystemException(AppHttpCodeEnum.ID_NUMBER_ERROR);

        Employee byUsername = employeeMapper.getByUsername(employeeDTO.getUsername());
        if (Objects.nonNull(byUsername)) throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);

        Employee employee = BeanCopyUtils.copyBean(employeeDTO, Employee.class);
        employee.setStatus(StatusConstant.ENABLE);
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        // 调用mapper
        employeeMapper.insertEmployee(employee);
        return Result.success();
    }


    /*
     * 员工分页
     * */
    @Override
    public PageVo getEmployeePage(EmployeePageQueryDTO pageQueryDTO) {
        if (pageQueryDTO.getPage() < PageConstant.MIN_PAGE_NUM || pageQueryDTO.getPageSize() < PageConstant.MIN_PAGE_NUM) {
            throw new SystemException(AppHttpCodeEnum.ERROR_PAGE);
        }
        // Mybatis 分页
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.selectEmployee(pageQueryDTO);  // 这里必须返回一个Page<?> 对象
        return new PageVo(page.getResult(), page.getTotal());
    }


    /*
     * 账号启用、禁止
     * */
    @Override
    public Result<String> changeStatus(Integer status, Long id) {
        if (Objects.isNull(id)) {
            return Result.error(AppHttpCodeEnum.EMPLOYEE_ID_IS_NULL.getMsg());
        }
        if (Objects.isNull(status)) {
            return Result.error(AppHttpCodeEnum.STATUS_IS_NULL.getMsg());
        }
        if (!status.equals(StatusConstant.DISABLE) && !status.equals(StatusConstant.ENABLE)) {
            return Result.error(AppHttpCodeEnum.STATUS_ERROR.getMsg());
        }
        if (employeeMapper.changeStatus(status, id).equals(StatusConstant.UPDATE_ERROR)) {
            return Result.error(AppHttpCodeEnum.UPDATE_ERROR.getMsg());
        }
        return Result.success();
    }

    /*
     * 根据id查询员工
     * */
    @Override
    public Result<EmployeeVo> getEmployeeById(Long id) {
        if (Objects.isNull(id)) {
            return Result.error(AppHttpCodeEnum.EMPLOYEE_ID_IS_NULL.getMsg());
        }
        Employee employee = employeeMapper.selectEmployeeById(id);
        if (Objects.isNull(employee)) {
            return Result.error(MessageConstant.EMPLOYEE_NOT_FOUNT);
        }
        EmployeeVo employeeVo = BeanCopyUtils.copyBean(employee, EmployeeVo.class);
        return Result.success(employeeVo);
    }

    /*
     * 编辑员工
     * */
    @Override
    public Result<String> updateEmp(EmployeeDTO employeeDTO) {
        if (!checkEmployeeDto(employeeDTO)) {
            return Result.error(MessageConstant.DATA_ERROR);
        }
        if (employeeMapper.updateEmp(employeeDTO).equals(StatusConstant.UPDATE_ERROR)) {
            return Result.error(AppHttpCodeEnum.UPDATE_ERROR.getMsg());
        }
        return Result.success();
    }


    /*
     * 修改密码
     * */
    @Override
    public Result<String> editPass(PasswordEditDTO passwordEditDTO) {
        if (Objects.isNull(passwordEditDTO.getEmpId())) {
            return Result.error(AppHttpCodeEnum.EMPLOYEE_ID_IS_NULL.getMsg());
        }
        if (!StringUtils.hasText(passwordEditDTO.getNewPassword())) {
            return Result.error(AppHttpCodeEnum.NEW_PASS_IS_NULL.getMsg());
        }
        if (!StringUtils.hasText(passwordEditDTO.getOldPassword())) {
            return Result.error(AppHttpCodeEnum.OLD_PASS_IS_NULL.getMsg());
        }
        if (!checkOldPassWord(passwordEditDTO)) {
            return Result.error(AppHttpCodeEnum.OLD_PASS_ERROR.getMsg());
        }
        passwordEditDTO.setNewPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        if (employeeMapper.editPass(passwordEditDTO).equals(StatusConstant.UPDATE_ERROR)) return Result.error(AppHttpCodeEnum.UPDATE_ERROR.getMsg());
        return Result.success();
    }


    /*
     * 封装对 EmployeeDTO 类的数据校验
     * */
    private boolean checkEmployeeDto(EmployeeDTO employeeDTO) {
        // 数据校验
        if (Objects.isNull(employeeDTO.getId())) {
            return false;
        }
        if (!StringUtils.hasText(employeeDTO.getUsername())) {
            return false;
        }
        if (!employeeDTO.getPhone().matches(RegEx.PHONE_REG)) {
            return false;
        }

        // 身份证格式校验
        if (employeeDTO.getIdNumber().length() == EmployeeConstant.ID_LENGTH_18) {
            return employeeDTO.getIdNumber().matches(RegEx.ID_CARD_REG18);
        } else if (employeeDTO.getIdNumber().length() == EmployeeConstant.ID_LENGTH_15) {
            return employeeDTO.getIdNumber().matches(RegEx.ID_CARD_REG15);
        } else return true;
    }


    /*
     *  根据员工id查询员工，对比旧密码
     * */
    private boolean checkOldPassWord(PasswordEditDTO passwordEditDTO) {
        Long id = passwordEditDTO.getEmpId();
        Employee employee = employeeMapper.selectEmployeeById(id);
        return DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes()).equals(employee.getPassword());
    }



}
